<template>
  <div>
    <div class="main-head flex-between container-fluid">
      <div class="title">
        <h1 v-text="$t('pro.invoice.title')"></h1>
      </div>
    </div>
    <div class="content container-fluid">
      <div class="portlet">
        <nav class="nav">
          <a
            @click="handleChange('depositData')"
            :class="{'active':tableName=='depositData'}"
            v-text="$t('pro.invoice.activity')"
          ></a>
          <a
            @click="handleChange('transactionData')"
            :class="{'active':tableName=='transactionData'}"
            v-text="$t('pro.invoice.transactions')"
          > activity</a>
        </nav>
        <!-- 表单 -->
        <a-table
          v-if="!!(tableName == 'depositData' ? depositData : transactionData) && (tableName == 'depositData' ? depositData : transactionData).length>0"
          :rowKey="record => record.id"
          :columns="getColumns"
          :dataSource="tableName == 'depositData' ? depositData : transactionData"
          :loading="listLoading"
          :pagination="false"
        >
          <div slot="createdAt" slot-scope="createdAt" v-if="tableName === 'depositData'">
            {{ createdAt | formatLentime }}
          </div>
          <div slot="createdAt" slot-scope="createdAt" v-else>
            {{ createdAt | formatMonth }}
          </div>

          <template slot="type" slot-scope="type, text">
            {{ transactionTypes.find(item => item.key == type).value || ' - '}}
          </template>

          <a slot="action" slot-scope="text" href="javascript:;" @click="handleDownload($event,text)">
            <a-icon :type="downloadType" style="font-size: 1.5rem"/>
          </a>
        </a-table>

        <div v-else>
          <a-empty
                  image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
            <span slot="description">{{$t('pro.campaigns.activeNotMess')}}</span>
          </a-empty>
        </div>

        <!-- 分页 -->
        <div v-if="!!(tableName == 'depositData' ? depositData : transactionData) && (tableName == 'depositData' ? depositData : transactionData).length>0"
             class="public-page-box">
          <a-pagination
              showSizeChanger
              showQuickJumper
              :pageSize.sync="pagination.pageSize"
              :total="pagination.total"
              v-model="pagination.current"
              @change="onShowSizeChange"
              @showSizeChange="onShowSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getRecharge, getInvoice } from '../../api/user'
import { parseTime, dateShortMonth, getDate } from '../../utils/time'
import { download3, download2 } from "../../utils/downLoad";
export default {
  filters: {
      formatLentime(val) {
          return parseTime(new Date(val), '{y}/{m}/{d}')
      },
      formatMonth(val) {
          return parseTime(new Date(val), '{y}/{m}')
      }
  },
  data() {
    return {
      tableName: 'depositData',
      columnList: [],
      listLoading: false,

      depositData: [],
      transactionData: [], //table组件显示的存款数据

      downloadType: 'download',
      pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '50'],
          current: 1,
          pageSize: 10,
          total: 500,
      },
      transactionList: [], //所有计算后的存款数据
      transactionPageList: [], //存款所有的分页信息集合
    }
  },
  computed: {
      getColumns() {
          if (this.tableName == 'depositData') {
              return this.$t('pro.invoice.columns');
          }else {
              let list = [];
              let list2 = list.concat(this.$t('pro.invoice.columns'))
              list2.splice(2,1);
              return list2;
          }
      },
      transactionTypes() {
          return this.$t('pro.admin.transactionTypes')
      },
  },
  methods: {
      handleChange(val) {
        this.tableName = val;
        if (val == 'depositData') {
            this.fetch();
        }else {
            let onlUser = this.$store.getters.userInfo || {};
            let starDate = onlUser.createdAt || new Date();
            let initDate = parseTime(starDate, '{y}-{m}-{d}');
            let xDate = parseTime(new Date, '{y}-{m}-{d}');
            let transactionData = [];
            //计算用户注册到现在为止有几个月份 包括本月所有加一
            let len = dateShortMonth(xDate, initDate) + 1;
            for(let i = 0;i > -len; i--) {
               transactionData.push({
                   id: i,
                   createdAt: getDate(xDate, "month", i), //根据日期返回指定月份的 到某个时间段的日期
                   totalType: 0,
               });
            }

            let list = transactionData || []; //用户注册到现在为止的每个月的统计
            this.pagination.total = list.length;
            this.transactionList = list;

            this.transactionInitPage(list);
        }
    },

      /*分页初始化*/
      transactionInitPage(list = []) {
          let pageList = [];
          let ind = 0;
          let start = 0;
          list.forEach((item, index) => {
              if (!!index && index%this.pagination.pageSize == 0) {
                  pageList[ind] = list.slice(start, index);
                  start = index;
                  ind++;
              }
          });
          //计算最后剩下部分
          if(list.length!=start) {
              pageList.push(list.slice(start, list.length))
          }
          this.transactionPageList = pageList;


          this.listLoading = true;
          this.transactionData = this.transactionPageList[this.pagination.current-1];
          setTimeout(() => {
              this.listLoading = false;
          }, 500)
      },

      //下载
    handleDownload(e, text) {
        e.preventDefault();
        //this.downloadType = "loading"; //待解决 当多条数据时，如何解决所有图表都变
        let params;
        if(this.tableName == 'depositData') {
            //存款
            params = {id:text.id, type: 0}
        }else {
            //交易  text.createdAt = 2019/12
            params = {start: text.createdAt+" 00:00:00" , type: 6}
        }
        this.listLoading = true;
        getInvoice(params).then(res => {
            console.log('------------');
            console.log(typeof res.data);
           /* download3(res.data);*/

             download2(res.data).then(res => {}).finally(() => { this.listLoading = false })
         }).finally(() => { this.listLoading = false })
    },

    onShowSizeChange(current, pageSize) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = current;

        //如何是存款分页，那么就从分页集合里取出等于页的数据段
        if(this.tableName == 'transactionData') {
            this.transactionInitPage(this.transactionList || []);
        }
    },

    fetch() {
          this.listLoading = true;
          let params = {
              type: 0, //存款
          };
          params.page = this.pagination.current;
          params.results = this.pagination.pageSize;
          params = JSON.parse(JSON.stringify(params));
          getRecharge(params).then(res => {
              let { code, data} = res.data;
              if (code == '200'){
                  this[this.tableName] = data.records;
                  this.pagination.total = data.size
              }
          }).finally(() => { this.listLoading = false })
      }
  },
  mounted() {
      this.fetch()
  }

}
</script>

<style lang="less" scoped>
  .spin-content{
    border: 1px solid #91d5ff;
    background-color: #e6f7ff;
    padding: 30px;
  }
.nav {
  // font-size: .8em;
  font-weight: 500;
  margin-bottom: 20px;
  > a {
    margin: 0 10px;
    padding: 10px 0;
    &::after {
      margin-top: 5px;
    }
  }
}
</style>
